package kr.hkit.powerjava.coffee.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

import kr.hkit.powerjava.coffee.dao.CoffeeDAO;
import kr.hkit.powerjava.coffee.dto.SalesRecord;

public class CoffeeService extends AbsService<SalesRecord> {

	ArrayList<SalesRecord> list;

	public CoffeeService(Scanner sc, Connection connection) {
		super(sc, connection);
		dao = new CoffeeDAO(connection);
	}

	@Override
	public SalesRecord inputItemInfo() {
		System.out.print("제품코드 제품단가 판매수량 마진율");
		SalesRecord record = new SalesRecord(sc.next().trim(), sc.nextInt(),
				sc.nextInt(), sc.nextDouble());
		return record;
	}

	@Override
	public void prnSubMenu(int sort) {
		System.out.print("1. 판매 금액 순 정렬 2. 마진액순 정렬");
		try {
			list = dao.listItems();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		switch (sort) {
		case 1:
			prnItemList(new Comparator<SalesRecord>() {

				@Override
				public int compare(SalesRecord o1, SalesRecord o2) {
					return o1.getSellingPrice() - o2.getSellingPrice();
				}
			});
			break;
		case 2:
			prnItemList(new Comparator<SalesRecord>() {

				@Override
				public int compare(SalesRecord o1, SalesRecord o2) {
					return o1.getMargin() - o2.getMargin();
				}
			});
			break;
		default:
			prnItemList(null);
		}
	}

	private void prnItemList(Comparator<SalesRecord> comparator) {
		if (comparator == null) {
			Collections.sort(list);
		} else {
			Collections.sort(list, comparator);
		}
		prnlist(list);
	}

	private void prnlist(ArrayList<SalesRecord> list2) {
		for (SalesRecord e : list) {
			System.out.println(e);
		}
	}

}
